package cn.rick.controller;

import cn.dev33.satoken.util.SaResult;
import cn.rick.entity.BuildMaterials;
import cn.rick.entity.Supplier;
import cn.rick.entity.SupplierBrand;
import cn.rick.entity.SupplierContact;
import cn.rick.service.IBuildMaterialsService;
import cn.rick.service.ISupplierBrandService;
import cn.rick.service.ISupplierContactService;
import cn.rick.service.ISupplierService;
import cn.rick.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author rick
 * @since 2022-11-16 09:26:11
 */
@RestController
@RequestMapping("/api/supplier")
@Api(value = "供应商控制器", tags = {"供应商控制器"})
public class SupplierController {

    @Resource
    private ISupplierService iSupplierService;
    @Resource
    private ISupplierBrandService iSupplierBrandService;
    @Resource
    private ISupplierContactService iSupplierContactService;
    @Resource
    private IBuildMaterialsService iBuildMaterialsService;

    @GetMapping("/getList")
    @ApiOperation("获取供应商列表")
    public SaResult getList(Supplier supplier, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Supplier> query = new LambdaQueryWrapper<>();
        query.orderByDesc(Supplier::getCreateTime);

        //供应商名称
        if (StringUtils.isNotEmpty(supplier.getName())) {
            query.like(Supplier::getName, supplier.getName());
        }
        //采购员
        if (StringUtils.isNotEmpty(supplier.getBuyUser())) {
            query.eq(Supplier::getBuyUser, supplier.getBuyUser());
        }
        //供应商类型
        if (StringUtils.isNotEmpty(supplier.getType())) {
            query.eq(Supplier::getType, supplier.getType());
        }
        //创建时间
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            query.between(Supplier::getCreateTime, startTime, endTime + " 23:59:59");
        }

        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Supplier> pageInfo = new PageInfo<>(iSupplierService.list(query));
        return SaResult.data(pageInfo);
    }

    @GetMapping("/getAllSupplierApi")
    @ApiOperation("获取所有供应商信息不需要参数")
    public SaResult getAllSupplier() {
        return SaResult.data(iSupplierService.list());
    }

    @PostMapping("/insert")
    @ApiOperation("新增供应商")
    @Transactional(rollbackFor = Exception.class)
    public SaResult insert(@RequestBody Map<String, Object> map) {
        try {
            Supplier supplier = JSONObject.parseObject(JSON.toJSONString(map), Supplier.class);
            supplier.setCreateTime(LocalDateTime.now());
            if (iSupplierService.save(supplier)) {
                List<SupplierBrand> brands = JSONArray.parseArray(JSONArray.toJSONString(map.get("tableBrand")), SupplierBrand.class);
                if (brands.size() != 0) {
                    brands.forEach(item -> {
                        item.setSupplierId(supplier.getId());
                    });
                    iSupplierBrandService.saveBatch(brands);
                }
                List<SupplierContact> contacts = JSONArray.parseArray(JSONArray.toJSONString(map.get("tableContact")), SupplierContact.class);
                if (contacts.size() != 0) {
                    contacts.forEach(item -> {
                        item.setSupplierId(supplier.getId());
                    });
                    iSupplierContactService.saveBatch(contacts);
                }
                return SaResult.ok("添加成功");
            } else {
                return SaResult.error("添加失败，请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("添加失败，请稍后再试");
        }
    }

    @PostMapping("/update")
    @ApiOperation("修改供应商")
    @Transactional(rollbackFor = Exception.class)
    public SaResult update(@RequestBody Map<String, Object> map) {
        try {
            Supplier supplier = JSONObject.parseObject(JSON.toJSONString(map), Supplier.class);
            supplier.setUpdateTime(LocalDateTime.now());
            if (iSupplierService.updateById(supplier)) {
                LambdaQueryWrapper<SupplierBrand> brandLambdaQueryWrapper = new LambdaQueryWrapper<>();
                brandLambdaQueryWrapper.eq(SupplierBrand::getSupplierId, supplier.getId());
                LambdaQueryWrapper<SupplierContact> contactLambdaQueryWrapper = new LambdaQueryWrapper<>();
                contactLambdaQueryWrapper.eq(SupplierContact::getSupplierId, supplier.getId());
                iSupplierContactService.remove(contactLambdaQueryWrapper);
                iSupplierBrandService.remove(brandLambdaQueryWrapper);

                List<SupplierBrand> brands = JSONArray.parseArray(JSONArray.toJSONString(map.get("tableBrand")), SupplierBrand.class);
                if (brands.size() != 0) {
                    brands.forEach(item -> {
                        item.setSupplierId(supplier.getId());
                    });
                    iSupplierBrandService.saveBatch(brands);
                }
                List<SupplierContact> contacts = JSONArray.parseArray(JSONArray.toJSONString(map.get("tableContact")), SupplierContact.class);
                if (contacts.size() != 0) {
                    contacts.forEach(item -> {
                        item.setSupplierId(supplier.getId());
                    });
                    iSupplierContactService.saveBatch(contacts);
                }
                return SaResult.ok("更新成功");
            } else {
                return SaResult.error("更新失败，请稍后再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("更新失败，请稍后再试");
        }
    }

    @GetMapping("/getContactById")
    @ApiOperation("获取供应商联系人信息")
    public SaResult getContactById(@RequestParam("id") Long id) {
        LambdaQueryWrapper<SupplierContact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SupplierContact::getSupplierId, id);
        try {
            List<SupplierContact> list = iSupplierContactService.list(queryWrapper);
            return SaResult.data(list);
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("查询失败");
        }
    }

    @GetMapping("/getBrandById")
    @ApiOperation("获取供应商品牌信息")
    public SaResult getBrandById(@RequestParam("id") Long id) {
        LambdaQueryWrapper<SupplierBrand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SupplierBrand::getSupplierId, id);
        try {
            List<SupplierBrand> list = iSupplierBrandService.list(queryWrapper);
            return SaResult.data(list);
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("查询失败");
        }
    }

    @DeleteMapping("/del/{id}")
    @ApiOperation("删除供应商")
    @Transactional(rollbackFor = Exception.class)
    public SaResult del(@PathVariable Long id) {
        try {
            LambdaQueryWrapper<BuildMaterials> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BuildMaterials::getSupplier, id);
            if (iBuildMaterialsService.list(queryWrapper).size() != 0) {
                return SaResult.error("删除失败，此供应商有相关联的主材料");
            }

            LambdaQueryWrapper<SupplierBrand> brandLambdaQueryWrapper = new LambdaQueryWrapper<>();
            brandLambdaQueryWrapper.eq(SupplierBrand::getSupplierId, id);
            LambdaQueryWrapper<SupplierContact> contactLambdaQueryWrapper = new LambdaQueryWrapper<>();
            contactLambdaQueryWrapper.eq(SupplierContact::getSupplierId, id);
            iSupplierBrandService.remove(brandLambdaQueryWrapper);
            iSupplierContactService.remove(contactLambdaQueryWrapper);

            if (iSupplierService.removeById(id)) {
                return SaResult.ok("删除成功");
            }

            return SaResult.error("删除失败,请稍后再试");
        } catch (Exception e) {
            e.printStackTrace();
            return SaResult.error("删除失败,请稍后再试");
        }
    }

}
